﻿#include "RecordScript.h"
#include <QFile>
#include <QTimer>
//#include <QTextStream>
#include "qtextstream.h"
#include <QReadWriteLock>
#include <QCoreApplication>
#include <QDir>
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include "PythonAgent.h"

namespace ScriptManager
{
    unsigned int LastSize = 0;

    RecordThread::RecordThread(QObject* parent) 
        : _file(new QFile(GlobalHelperInstance->getRecordScriptFilePath()))
        , _IO(new QTextStream(_file))
    {
        QDir dir(qApp->applicationDirPath() + "/../tempIO");
        if (!dir.exists())
        {
            dir.mkdir(qApp->applicationDirPath() + "/../tempIO");
        }
        //connect(IBaseSignalInstance, &BaseModule::IBaseSignal::signal_updateProjectTempDir, this, &RecordThread::slot_updateProjectTempDir);
    }

    void RecordThread::slot_updateProjectTempDir()
    {
        _file->setFileName(GlobalHelperInstance->getRecordScriptFilePath());
    }

    RecordThread::~RecordThread()
    {

        delete _IO;
        _file->remove();
        _file->deleteLater();
    }


    void RecordThread::pause()
    {
        _states = -1;
    }

    void RecordThread::stop()
    {
        _states = 1;
    }

    void RecordThread::reStart()
    {
        LastSize = 0;
        _states = 0;
        if (_file->open(QIODevice::WriteOnly))
        {
            QTextStream _stream(_file);
            _stream.setCodec("UTF-8");
            _stream << "";
        }
        _file->close();
    }


    void RecordThread::run()
    {
        while (true)
        {
            if (_states == 1) return;
            this->msleep(500);
            writeRecordScriptFile();
        }
    }

    void RecordThread::writeRecordScriptFile()
    {
        if (_states != 0) return;

        QStringList codelist = PythonAgent::getInstance()->getcodelist();
        unsigned int CurrentSize = codelist.size();
        if (CurrentSize <= LastSize) return;

        bool ok = false;
        ok = _file->open(QIODevice::WriteOnly | QIODevice::Append);

        if (!ok) return;

        QTextStream _stream(_file);
        _stream.setCodec("UTF-8");
        for (int i = LastSize; i < CurrentSize; i++)
        {
            _stream << codelist.at(i) << endl;
        }

        LastSize = CurrentSize;
        _file->close();
    }
}
